#coding=utf-8

from app.web.comm.test_method import RunMain
import unittest
import json
from app.web.comm.get_data import GetData
import requests
import time
from app.web.comm.random_number import CreateRanDom
from app.web.comm.test_data import TestData
import time
from app.web.comm.operate_excel import OperateExcel
from app.web.comm.operate_header import  OperationHeader
from app.web.comm.HTMLTestRunner import  HTMLTestRunner
import requests
from app.web.comm.check import Check
from pyquery import PyQuery as pq
import re
# from lxml import etree
# from HTMLParser import HTMLParser
from app.web.casesuit.config_shanghu  import  *
import re
from app.web.comm.operate_json import  OperationJson
from app.web.conf.config import  *

from app.web.conf.config import base_url_backend

G = GetData()
R = RunMain()
C = Check()
CR = CreateRanDom()
Op=OperateExcel()

class LoginBackend():

    """登录管理后台"""
    # @unittest.skip("fail")
    def test_login_backend(self):
        self.opera = OperationJson()
        """get获取csrftoken"""
        test_url = base_url_backend+'/site/login'
        s=requests.Session()#保存session
        res = s.get(url=test_url)
        text=res.text
        # print(text)

        # global csrftoken
        """提取页面元素"""
        # html = res.text
        # doc = pq(html)#创建一个对象
        # doc3 = doc("meta:nth-child(4)") # 提取第四个,html页面提取csrftoken
        # csrftoken = doc3.attr('content')  # 提取字符串
        csrftoken=re.compile('<meta name="csrf-token" content="+(.*?)[">]').findall(text)#正则提取
        print("csrftoken:%s"%csrftoken)

        # cookie=res.headers['Set-Cookie']
        global cookie1
        cooki=res.cookies
        cookie1=requests.utils.dict_from_cookiejar(cooki)#提取dict格式cookie
        print("cookie1:%s"%cookie1)

        # Op_header = OperationHeader(res)
        # Op_header.write_cookie()

        """post接口获取登录token"""
        request_data={"_csrf-backend":csrftoken,
        "LoginForm[password]": "dev@gaopeng",
        "LoginForm[rememberMe]": "1",
        "LoginForm[username]": "admin"
        }

        # res=R.run_main(url=test_url1, method=test_method1,data=request_data1, allow_redirects=True)#,header=headers
        cookie1['advanced-backend']="cfaspih6pd9iebu9m8o59dgc52"
        res2=requests.post(url=test_url,data=request_data, cookies=cookie1)#, allow_redirects=True
        print(res2.headers)
        # set_cookie=res2.headers['Set-Cookie']
        # global token
        # token = set_cookie[6:38]
        # print(token)
        print("登录成功")
        # Op_header = OperationHeader(res2)
        # Op_header.write_cookie()#将cookie写入cookie.json文件

        cooki2=res2.cookies
        cookie2=requests.utils.dict_from_cookiejar(cooki2)
        print("cookie2:%s"%cookie2)
        cookie=dict(cookie1,**cookie2)
        cook=json.dumps(cookie,ensure_ascii=False,indent=4)
        self.opera.write_cookie_data(cook.encode('utf-8'))
        return csrftoken,cook

    def test_cerficate_merchant(self,taxpayer_num,username):
        """管理后台审核工单"""
        global work_order_id,csrftoken,result_cookie
        tokens=self.test_login_backend()
        csrftoken = tokens[0]
        result_cookie=result_cookie = json.loads(tokens[1])
        # print("cookie如下：")
        # print(result_cookie )
        # print(type(result_cookie ))
        work_order_id = C.coonect_db(database='workorder',
                                     sql="select work_order_id from wo_work_order_merchant  where tax_code='%s'" % taxpayer_num)[0]  # 获取工单id

        print(work_order_id)

        id_num = C.coonect_db(database='fpmerchant', sql="select id from m_service_provider where username='%s'" % username)[0]  # 获取服务商id
        print(id_num)
        test_url1 = base_url_backend +"/workorder/work-order/confirm?id=%s" % work_order_id
        test_method = 'post'
        test_data = {"_csrf-backend":csrftoken,
                     "ConfirmForm[service_provider_id]": id_num,  # 服务商id
                     "ConfirmForm[action]": 1,  # 审核通过
                     "ConfirmForm[note]": "接口"
                     }
        res = R.run_main(url=test_url1, method=test_method, data=test_data, cookie=result_cookie)
        print("请求url:{}".format(test_url1))
        print("---------")
        print("请求data:{}".format(test_data))
        print(res)

    # """填写物流信息"""
        test_url2 = base_url_backend +"/workorder/payment/pay-info-min"
        test_method = 'post'
        test_data = {"_csrf-backend": csrftoken, 'work_order_id': work_order_id}
        res = R.run_main(url=test_url2, method=test_method, data=test_data, cookie=result_cookie)
        print(res)
        print("物流信息填写完成")

    # """确认支付"""
        test_url3 =base_url_backend +"/workorder/work-order/confirm-paid"
        test_method = 'post'
        test_data = {"_csrf-backend": csrftoken, 'id': work_order_id, "express_no": "", "express_name": ""}
        res = R.run_main(url=test_url3, method=test_method, data=test_data, cookie=result_cookie)
        print(res)
        print("审核完成")


if __name__=="__main__":
    taxpayer_num="GAPEN7cdef1l31k"
    username="1811108@gaopeng.com"
    # LoginBackend().test_login_backend()
    LoginBackend().test_cerficate_merchant(taxpayer_num,username)

